package y2016.test;

import java.io.*;

public class CopyFile {
    private static boolean flag = true;

    private void copyFile(File sourcefile, File targetFile) {
        if (targetFile.exists()) {
            System.out.println(targetFile.getAbsolutePath() + "已经存在");
            return;
        }
        InputStream is = null;
        BufferedInputStream bis = null;

        OutputStream os = null;
        BufferedOutputStream bos = null;

        try {
            is = new FileInputStream(sourcefile);
            bis = new BufferedInputStream(is);

            os = new FileOutputStream(targetFile);
            bos = new BufferedOutputStream(os);

            byte[] b = new byte[1024 * 5];
            int len = 0;

            while (((len = bis.read(b)) != -1) && (flag)) {

                bos.write(b, 0, len);
            }
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                os.close();
                bis.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (flag && sourcefile.length() == targetFile.length()) {
                System.out.println(sourcefile.getName() + "复制成功");
            } else {
                System.out.println("操作失败");
                boolean bool = targetFile.delete();
                if (bool) {
                    System.out.println("成功清除");
                } else {
                    System.out.println("清除失败");
                }
            }

        }


    }

    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     *
     * @param source
     * @param target
     * @throws IOException
     */
    public void copyFolder(File source, File target) {
        if (source.isDirectory()) {
            if (!target.exists()) {
                target.mkdir();
            }
            String files[] = source.list();
            for (String file : files) {
                File srcFile = new File(source, file);
                File destFile = new File(target, file);
                // 递归复制
                copyFolder(srcFile, destFile);
            }

        } else {//如果不是目录，是一个文件。

            copyFile(source, target);
        }
    }

    public void copyFileFloder(String sourcePath, String targetPath) {
        File sourceFile = new File(sourcePath);
        File targetFile = new File(targetPath, sourceFile.getName());

        if (sourceFile.isDirectory()) {
            copyFolder(sourceFile, targetFile);
        } else {
            copyFile(sourceFile, targetFile);
        }
    }


}



